package com.dq.controller.api.staff;

import com.dq.context.event.user.UserEditPhoneEvent;
import com.dq.exception.customException.AdminException;
import com.dq.controller.api.merchant.in.request.EditPhoneRequest;
import com.dq.controller.api.merchant.in.request.EditPwdRequest;
import com.dq.controller.in.TrackQuery;
import com.dq.controller.in.request.TrackAdd;
import com.dq.vo.ListVo;
import com.dq.vo.Vo;
import com.dq.domain.base.AbstractEntity;
import com.dq.domain.record.MaintainRecord;
import com.dq.domain.record.ServiceRecord;
import com.dq.domain.reward.Reward;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.domain.sys.user.user.WxUser;
import com.dq.service.AllService;
import com.dq.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author luchangtong
 * @Date 2019/12/2 10:03
 */
@RestController
@RequestMapping("/staff/my")
@Api(description = "技师 我的")
public class StaffUserMyController extends AllService {
    @Value("${oss-show-url}")
    private String ossShowUrl;


    @ApiOperation("我的信息")
    @GetMapping("StaffMyInfo")
    public Vo StaffMyInfo()throws AdminException{
        SysUser sysUser = shiroService.getUser();
        if(null==sysUser){
            throw new AdminException("您还未登陆");
        }
        StaffUser user = dao.get(StaffUser.class,sysUser.getId());
        if(null==user){
            throw new AdminException("用户信息不存在");
        }
        Long averageScore =evaluationRecordRepository.findByScore(user.getId());
        Long num = evaluationRecordRepository.findByNum(user.getId());
        BigDecimal average;
        if(num == 0L){
            average = new BigDecimal("0");
        }else {
            average = new BigDecimal(averageScore.toString()).divide(new BigDecimal(num.toString()),1, RoundingMode.HALF_UP);
        }
        return new Vo(user.toStaffUserInfo(num,average));
    }

    @ApiOperation("我的提成")
    @GetMapping("myRoyalty/{beginTime}/{endTime}")
    public Vo myRoyalty(@PathVariable @ApiParam("开始时间") Long beginTime ,
                         @PathVariable @ApiParam("结束时间")Long endTime) throws AdminException{
        SysUser sysUser = shiroService.getUser();
        if(null==sysUser){
            throw new AdminException("您还未登陆");
        }
        //业绩提成
        BigDecimal royalty = royaltyRecordRepository.getSumPrice(sysUser);
        //奖励
        BigDecimal special = rewardRepository.getReward((StaffUser) sysUser, Reward.RewardCategory.special,beginTime,endTime);
        BigDecimal random = rewardRepository.getReward((StaffUser) sysUser, Reward.RewardCategory.random,beginTime,endTime);
        BigDecimal manualPrice = serviceRecordRepository.manualPrice((StaffUser) sysUser, ServiceRecord.ServiceStatus.endService,beginTime,endTime);
        HashMap<String,Object> map = new HashMap<>();
        map.put("royalty",royalty);
        map.put("special",special);
        map.put("random",random);
        map.put("manualPrice",manualPrice);
        return new Vo(map);
    }


    @ApiOperation("维护记录")
    @PostMapping("TrackRecord")
    public ListVo TrackRecord(@RequestBody TrackQuery trackQuery)throws AdminException{
        if(null==trackQuery.getPage() || null==trackQuery.getSize()){
            throw new AdminException("缺少必要的请求参数");
        }
        List<MaintainRecord> maintainRecordList = maintainRecordService.findByWhere(trackQuery);
        Long totalNum = maintainRecordService.countByWhere(trackQuery);
        List<MaintainRecord.StaffTrackListVo> list = new ArrayList<>();
        maintainRecordList.forEach(trackRecord -> {
            list.add(trackRecord.toStaffTrackListVo());
        });
        return new ListVo(list,totalNum);
    }

    @ApiOperation("维护详情")
    @GetMapping("trackInfo/{id}")
    public Vo trackInfo(@PathVariable @ApiParam("id") Long id) throws AdminException{
        MaintainRecord maintainRecord = dao.get(MaintainRecord.class,id);
        if(maintainRecord == null){
            throw new AdminException("无此记录");
        }
        return new Vo(maintainRecord.toStaffTrackListVo());
    }

    @ApiOperation("维护")
    @PostMapping("editTrack")
    public Vo editTrack(@RequestBody TrackAdd trackAdd)throws AdminException{
        MaintainRecord maintainRecord = dao.get(MaintainRecord.class,trackAdd.getId());
        if(maintainRecord == null){
            throw new AdminException("无此记录");
        }
        if(StringUtils.isEmpty(maintainRecord.getTrackNo())){
            maintainRecord.setTrackNo(AbstractEntity.generyStrAndMstime(""));
        }
        maintainRecord.setMaintainTime(System.currentTimeMillis());
        maintainRecord.setMaintainType(trackAdd.getMaintainType());
        maintainRecord.setMaintainStatus(MaintainRecord.MaintainStatus.visited);
        maintainRecord.setMaintainContent(trackAdd.getMaintainContent());
        maintainRecord.setVoucher(trackAdd.getVoucher());
        maintainRecordRepository.save(maintainRecord);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("顾客维护记录")
    @GetMapping("trackbyid/{id}/{page}/{size}")
    public ListVo trackbyid(@PathVariable Long id,@PathVariable Integer page,@PathVariable Integer size) throws AdminException{
        WxUser wxUser = dao.get(WxUser.class,id);
        if(wxUser == null){
            throw new AdminException("请重新选择顾客");
        }
        List<MaintainRecord> maintainRecordList = maintainRecordRepository.findByWxUserOrderByCreateTimeDesc(wxUser, PageableUtil.get(page,size)).getContent();
        Long total = maintainRecordRepository.countByWxUser(wxUser);
        List<MaintainRecord.StaffTrackListVo> listVos = new ArrayList<>();
        maintainRecordList.forEach(trackRecord -> {
            listVos.add(trackRecord.toStaffTrackListVo());
        });
        return new ListVo(listVos,total);
    }

    @PostMapping("/editPwd")
    @ApiOperation("修改当前用户密码")
    public Vo editPwd(@RequestBody EditPwdRequest editPwdRequest)throws AdminException{
        SysUser user = shiroService.getUser();
        StaffUser staffUser = dao.get(StaffUser.class,user.getId());
        if(!PasswordUtil.verify(editPwdRequest.getOldPwd(),staffUser.getPassword())){throw new AdminException("旧密码不正确");}
        staffUser.setPassword(sysUserService.getPassword(editPwdRequest.getNewPwd()));
        staffUserRepository.save(staffUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(staffUser));
    }

    @PostMapping("/editPhone/sendSms")
    @ApiOperation("修改当前用户手机号发送验证码")
    public Vo editPhoneSendSms(){
        StaffUser staffUser = (StaffUser)shiroService.getUser();
        String smsCode = RandomUtil.getNumber(6);
        Map<String, Object> map = new HashMap<>();
        map.put("phone", staffUser.getUsername());
        map.put("smsCode", smsCode);
        eventPublisher.publishEvent(new UserEditPhoneEvent(map));
        shiroService.setSmsCaptchaCache(smsCode,staffUser.getUsername());
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/editPhone")
    @ApiOperation("修改当前用户手机号")
    public Vo editPhone(@RequestBody EditPhoneRequest editPhoneRequest)throws AdminException{
        if(!EditCheckUtil.isMobileNO(editPhoneRequest.getPhone())){throw new AdminException("手机号格式不正确");}
        String cacheSms = shiroService.getSmsCaptchaCache(editPhoneRequest.getPhone());
        if(!cacheSms.equals(editPhoneRequest.getSmdCode())){throw new AdminException("验证码不正确");}
        StaffUser staffUser = (StaffUser) shiroService.getUser();
        staffUser.setUsername(editPhoneRequest.getPhone());
        staffUserRepository.save(staffUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(staffUser));
    }

    @GetMapping("/editNickName/{nickName}")
    @ApiOperation("修改昵称")
    public Vo editNickName(@PathVariable String nickName)throws AdminException{
        SysUser sysUser = shiroService.getUser();
        StaffUser staffUser = dao.get(StaffUser.class,sysUser.getId());
        staffUser.setLocalNickName(nickName);
        staffUserRepository.save(staffUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(staffUser));
    }

    @GetMapping("/signOut")
    @ApiOperation("退出登陆")
    public Vo signOut(){
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/userImgEdit")
    @ApiOperation("用户头像修改")
    public Vo userImgEdit(@ApiParam(value = "用户图片") MultipartFile file)throws IOException,AdminException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!EditCheckUtil.isImage(suffix)) {
            throw new AdminException("图片格式不正确");
        }
        SysUser user = shiroService.getUser();
        StaffUser staffUser = dao.get(StaffUser.class, user.getId());
        String fileName = ossService.upload(FileUtil.save(file));
        staffUser.setHeadImg(ossShowUrl + fileName);
        staffUserRepository.save(staffUser);
        return new Vo(ossShowUrl + fileName);
    }
}
